package com.view;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.controller.GPSLogManager;
import com.controller.UserManager;
import com.domain.AppUser;
import com.log.GPSLogEntry;


@SuppressWarnings("serial")
public class PostRegistryLogServlet extends HttpServlet{
	private static final Logger log = Logger.getLogger(PostRegistryLogServlet.class.getName());
	
	private UserManager userManager = new UserManager();
	private GPSLogManager logManager = new GPSLogManager();
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req,resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		try{
			double longitude = Double.parseDouble(req.getParameter("Longitude"));
			double latitude = Double.parseDouble(req.getParameter("Latitude"));
			SimpleDateFormat dateFormat = new SimpleDateFormat("EEE-MMM-d HH:mm:ss yyyy",Locale.US);
			Date postDate = dateFormat.parse(req.getParameter("Date"));
			String username = req.getParameter("Username");
			String password = req.getParameter("Password");
			AppUser user = new AppUser(username,password,null,null);
			if(userManager.isUserValid(user)){
				user = userManager.searchAppUser(username);
			}else{
				resp.getWriter().write("false");
				return;
			}
			String deviceName = req.getParameter("DeviceName");
			GPSLogEntry logEntry = new GPSLogEntry(user.getUserName(),deviceName,latitude,longitude,postDate);
			logManager.registerLogEntry(logEntry);
			resp.getWriter().write("true");
		}catch(Exception e){
			log.severe(e.getMessage());
		}
	}
	
}
